--- 此脚本的环境：  nginx 内部，不是运行在 redis 内部

--- 启动调试
--local mobdebug = require("luaScript.initial.mobdebug");
--mobdebug.start();
--导入自定义的基础模块
--local basic = require("luaScript.module.common.basic");
--导入自定义的 dataType 模块
local redisExecutor = require("luaScript.redis.RedisOperator");


--读取get参数
--local uri_args = ngx.req.get_uri_args()
--读取post参数
ngx.req.read_body();
--local uri_args = ngx.req.get_post_args()
local data = ngx.req.get_body_data(); --获取消息体

--ngx.say(data)

local args = cjson.decode(data);
local goodId = args["seckillGoodId"];
local userId = args["userId"];

--ngx.say("goodId=" .. goodId)
--ngx.say("userId=" .. userId)
local errorOut = { resp_code = -1, resp_msg = "限流出错", datas = {} };

local key="rate_limiter:seckill:"..goodId;

-- 获取 sha编码的命令
-- /usr/local/redis/bin/redis-cli script load "$(cat  /work/develop/LuaDemoProject/src/luaScript/redis/rate_limiter.lua)"
-- /usr/local/redis/bin/redis-cli  script exists  e4e49e4c7b23f0bf7a2bfee73e8a01629e33324b

--local rateLimiterSha = "e4e49e4c7b23f0bf7a2bfee73e8a01629e33324b";
--eg
-- /usr/local/redis/bin/redis-cli  --eval   /work/develop/LuaDemoProject/src/luaScript/redis/rate_limiter.lua rate_limiter:seckill:1 , init 1  1

local rateLimiterSha = nil;
--创建自定义的redis操作对象
local red = redisExecutor:new();
--打开连接
red:open();

-- 获取限流 lua 脚本的sha1 编码
rateLimiterSha=red:getValue("lua:sha1:rate_limiter");

-- redis 没有缓存秒杀脚本
if not rateLimiterSha or rateLimiterSha == ngx.null then
    errorOut.resp_msg="秒杀还未启动,请先设置商品";
    ngx.say(cjson.encode(errorOut));
    --归还连接到连接池
    red:close();
    return ;
end

local connection=red:getConnection();
local resp, err = connection:evalsha(rateLimiterSha, 1,key,"acquire","1");
--归还连接到连接池
red:close();

if not resp or resp == ngx.null then
    errorOut.resp_msg=err;
    ngx.say(cjson.encode(errorOut));
    return ;
end

local flag = tonumber(resp);
--ngx.say("flag="..flag);
if flag ~= 1 then
    errorOut.resp_msg = "抱歉，被限流了";
    ngx.say(cjson.encode(errorOut));
    ngx.exit(ngx.HTTP_UNAUTHORIZED);
end
return;